package com.jyh.blog.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyh.blog.dao.ArticleDao;
import com.jyh.blog.dao.CategoryDao;
import com.jyh.blog.dto.CategoryBackDTO;
import com.jyh.blog.dto.CategoryDTO;
import com.jyh.blog.entity.Article;
import com.jyh.blog.entity.Category;
import com.jyh.blog.exception.MyException;
import com.jyh.blog.service.CategoryService;
import com.jyh.blog.utils.PageUtils;
import com.jyh.blog.vo.ConditionVO;
import com.jyh.blog.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;

/**
 * (Category)表服务实现类
 *
 * @author jyh
 * @since 2023-01-18 13:49:24
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private ArticleDao articleDao;

    @Override
    public void addOrUpdate(Category category) {
        //查询标签是否存在
        Category existCategory = this.getOne(new LambdaQueryWrapper<Category>().select(Category::getId).eq(Category::getName, category.getName()));
        //需要修改的标签名称存在，并且与当前传入的标签id不一样时，报错
        if (Objects.nonNull(existCategory) && !existCategory.getId().equals(existCategory.getId())) {
            throw new MyException("分类名已存在");
        }
        this.saveOrUpdate(category);
    }

    @Override
    public PageResult<CategoryBackDTO> categoryBackList(ConditionVO condition) {
        String keywords = condition.getKeywords();
        //查询分类数量
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.like(!ObjectUtils.isEmpty(keywords), Category::getName, keywords);
        int count = this.count(lqw);
        if(count==0){
            return new PageResult<>();
        }
        //条件查询
        List<CategoryBackDTO> records = categoryDao.categoryListBack(PageUtils.getLimitCurrent(),PageUtils.getSize(),keywords);

        return new PageResult(records,count);
    }

    @Override
    public void deleteCategoryById(String id) {
        //有文章使用不能删除分类
        Integer count = articleDao.selectCount(new LambdaQueryWrapper<Article>().eq(Article::getCategoryId, id));
        if(count>0){
            throw  new MyException("有文章使用该分类，请删除对应文章后重试");
        }
        categoryDao.deleteById(id);
    }

    @Override
    public List<CategoryDTO> categoryList() {
        return categoryDao.categoryList();
    }
}

